﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace SURLService
{
    class URLEntry
    {
        public string URL;
        //public int Count;
    }

    class SURLDictionary
    {
        private URLEntry[] _URLEntries;
        private int _entryCount;
        
        public SURLDictionary(int size)
        {
            _URLEntries = new URLEntry[size];
            _entryCount = 0;
        }

        public string Get(int id)
        {
            string ret = null;
            if (id >= 0 && id < _URLEntries.Length && _URLEntries[id] != null)
            {
                ret = _URLEntries[id].URL;
            }
            return ret;
        }

        public int New(string url)
        {
            int id = NewID();
            _URLEntries[id] = new URLEntry()
            {
                URL = url
            };
            return id;
        }

        public void Set(int id, string url)
        {
            _URLEntries[id] = new URLEntry()
            {
                URL = url
            };
        }

        internal int NewID()
        {
            int ret, newEntryCount;

            do
            {
                ret = _entryCount;
                newEntryCount = ret + 1;
            } while (ret != Interlocked.CompareExchange(ref _entryCount, newEntryCount, ret));

            return ret;
        }

        public void Dump()
        {
            Console.WriteLine("Item amount {0}", _entryCount);
            for (int i = 0; i < _entryCount; ++i)
            {
                Console.WriteLine("{0}: {1}", i, _URLEntries[i].URL);
            }
        }
    }
}
